from QQLoginTool.QQtool import OAuthQQ
from rest_framework_jwt.settings import api_settings
from oauth.serializers import OAuthQQSerializer
from .models import OAuthQQUser
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework import status
from django.conf import settings
from rest_framework.response import Response
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from carts.utils import merge_cart_cookie_redis

# Create your views here.


class OAuthQQURLView(APIView):
    """
    qq实现获取url登入地址
    """
    def get(self, request):
        # 接收前端传递的state
        state = request.query_params.get('state')
        if not state:
            state = '/'
        # 构建url
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        url = oauth.get_qq_url()

        # 返回url

        return Response(
            {'login_url': url}
        )


class OAuthQQView(CreateAPIView):

    serializer_class = OAuthQQSerializer

    def get(self, request):
        """
        获取QQ openid唯一标识符
        :param request:
        :return:
        """

        # 获取code
        code = request.query_params.get('code')
        if not code:
            return Response({'message':'缺少code值'}, status=status.HTTP_401_UNAUTHORIZED)

        # 通过code获取access_token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        access_token = oauth.get_access_token(code)

        # 通过access_token获取openid
        openid = oauth.get_open_id(access_token)

        # 判断openid时候判断
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未判定过
            tjs=TJS(settings.SECRET_KEY, 300)
            token=tjs.dumps({'openid':openid}).decode()
            return Response({'access_token':token})
        # 绑定过
        user = qq_user.user

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        response = Response(
            {
                'username': user.username,
                'user_id': user.id,
                'token': token,
            }
        )
        response = merge_cart_cookie_redis(request, response, user)

        return response

    def post(self, request, *args, **kwargs):

        response = super().post(request, *args, **kwargs)
        user = request.user
        response = merge_cart_cookie_redis(request, response, user)

        return response

